package com.angel.bo.common.util;

import com.angel.bo.beans.jwt.JwtInfo;
import com.angel.bo.common.constant.CommonConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.util.Date;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 17:31 2018/1/29 
 */
public class JwtUtil {
    private static  RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();


    /**
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description:
     * @Date: 17:04 2018/1/29
     */
    public static String generateToken(JwtInfo jwtInfo,String priKeyPath,int expire) throws Exception {
        return Jwts.builder()
                .claim(CommonConstants.JWT_USER_ID,jwtInfo.getUserId())
                .claim(CommonConstants.JWT_LOGIN_NAME,jwtInfo.getLoginName())
                .claim(CommonConstants.JWT_USER_NAME,jwtInfo.getUserName())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKeyPath))
                .compact();
    }


    /**
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description: 解析token
     * @Date: 17:12 2018/1/29
     */
    public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
        return Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
    }


    /**
     *
     * @param token
     * @param pubKeyPath
     * @return
     * @throws Exception
     */
    public static JwtInfo getInfoFromToken(String token, String pubKeyPath)throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
        Claims body = claimsJws.getBody();
        String userId = StringHelper.getObjectValue(body.get(CommonConstants.JWT_USER_ID));
        String userName = StringHelper.getObjectValue(body.get(CommonConstants.JWT_USER_NAME));
        String loginName  = StringHelper.getObjectValue(body.get(CommonConstants.JWT_LOGIN_NAME));
        Date expirDate = body.getExpiration();
        return new JwtInfo(userId,loginName,userName,expirDate);
    }
    

}
